﻿# -*- coding:utf-8 -*-
#
# Система учета компьютерной техники  
#
# Исторический музей
#
from django.db import models
from django.contrib.auth.models import User

from shm import fields #PhonesField#, PhonesFormField,  PhonesWidget

#class CatDepartment(models.Model):
#    name = models.CharField(max_length=64, verbose_name="Наименование")



#class Phone(models.Model):
class Phone(models.Model):
    number = models.CharField(max_length=64, verbose_name="Номер")
    type = models.CharField(max_length=16, blank=True, verbose_name="Тип")
    room = models.CharField(max_length=8, blank=True, verbose_name="Комната")
    
    class Meta:
        ordering = ['number']

    def __unicode__(self):
        return self.number 


class Department(models.Model):
    parent = models.ForeignKey("self", blank=True, null=True, verbose_name="Головной отдел")
    name = models.CharField(max_length=64, verbose_name="Наименование")
    room = models.CharField(max_length=8, blank=True, verbose_name="Комната")
    phone = fields.PhonesField(Phone, blank=True, null=True, verbose_name=u"Телефон")
    virtual = models.BooleanField(verbose_name="Фиктивный отдел")
    code = models.IntegerField(default=0, verbose_name="Код отдела", editable=False)
    icon = models.ImageField(upload_to='files/shm/department/img/',  blank=True, verbose_name="Изображение")
    level = models.IntegerField(blank=True, default=1, verbose_name="уровень", editable=False)
    sort = models.IntegerField(blank=True, default=10, verbose_name="Сортировка")
    have_child = models.BooleanField(verbose_name="дочерние узлы", editable=False)
    
    
    class Meta:
        ordering = ['-sort', 'name']

    def __unicode__(self):
        return u'%s' % self.name

    def update_have_child(self):
        self.have_child = bool(self.department_set.count())

    def save(self, *args, **kwargs):
        if self.pk:
            try:
                old_obj = self.__class__.objects.get(pk=self.pk)
                if old_obj.icon:
                    if old_obj.icon.path != self.icon.path:
                        path = old_obj.icon.path
                        default_storage.delete(path)
            except self.__class__.DoesNotExist:
                pass

        # проверка наличия дочерних узлов     
        self.update_have_child()      
                
        super(Department, self).save(*args, **kwargs)
        
        # установка флага у родительского узла
        if self.parent: 
            self.parent.have_child = True  
            self.parent.save()



class Employee (models.Model):
    department = models.ForeignKey(Department)
    last_name = models.CharField(max_length=64, verbose_name="Фамилия")               # last name
    first_name = models.CharField(max_length=64, blank=True, verbose_name="Имя")      # first name
    patronymic = models.CharField(max_length=64, blank=True, verbose_name="Отчество") # patronymic
    post = models.CharField(max_length=128, blank=True, verbose_name="Должность")
    it_staff = models.BooleanField(verbose_name="Сотрудник IT")
    boss = models.BooleanField(verbose_name="Руководитель")
    fired = models.BooleanField(verbose_name="Уволенный") #уволенный
    responsible = models.BooleanField(verbose_name="Материально ответственное лицо")#The materially responsible person #  Материально ответственное лицо
    phone = models.ManyToManyField(Phone, blank=True, null=True, verbose_name="Телефон")

    class Meta:
        ordering = ['last_name']

    def __unicode__(self):
        return u'%s %s %s' % (self.last_name, self.first_name, self.patronymic)

		

